CODE 72. Rotate List

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/10/09/2013-10-09-CODE 72 Rotate List/

访问原文「CODE 72. Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public ListNode rotateRight(ListNode head, int n) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
if (null == head) {
return null;
}
ListNode round1 = null;
ListNode p = head;
int length = 0;
while (null != p) {
ListNode node = new ListNode(p.val);
node.next = round1;
p = p.next;
round1 = node;
length++;
}
if (n % length == 0) {
return head;
} else {
n = n % length;
}
int num = 0;
ListNode round2 = null;
ListNode p1 = round1;
while (num < n) {
ListNode node = new ListNode(p1.val);
node.next = round2;
p1 = p1.next;
round2 = node;
num++;
}
ListNode round3 = new ListNode(0);
ListNode round3Cpy = round3;
ListNode p2 = round2;
while (null != p2) {
ListNode node = new ListNode(p2.val);
p2 = p2.next;
round3Cpy.next = node;
round3Cpy = round3Cpy.next;
}
while (null != p1) {
ListNode node = new ListNode(p1.val);
node.next = round3Cpy.next;
round3Cpy.next = node;
p1 = p1.next;
}
return round3.next;
}
Jerky Lu wechat
欢迎加入微信公众号